import os
from osgeo import ogr
# Get Shapefile Feature Count
def getShpFeatureCount():
    daShapefile = r"data\Search_Polygon.shp"
    driver = ogr.GetDriverByName('ESRI Shapefile')
    # 0 means read-only. 1 means writeable.
    dataSource = driver.Open(daShapefile, 0)
    # Check to see if shapefile is found.
    if dataSource is None:
        print( 'Could not open %s' %daShapefile)
    else:
        print('Opened %s' %daShapefile )
        layer = dataSource.GetLayer()
        featureCount = layer.GetFeatureCount()
        print("Number of features is: %d" %featureCount)
    dataSource.Destroy()
# Get SpatialRef and Extent from a Layer
def getLayerSpatialInfo():
    shapefile = r"data\Search_Polygon.shp"
    driver = ogr.GetDriverByName("ESRI Shapefile")
    dataSource = driver.Open(shapefile, 0)
    layer = dataSource.GetLayer()
    print("空间参考:",layer.GetSpatialRef())
    print("空间范围:",layer.GetExtent())
    dataSource.Destroy()

def getFilterbyattribute():
    shapefile = r"data\Search_Polygon.shp"
    driver = ogr.GetDriverByName("ESRI Shapefile")
    dataSource = driver.Open(shapefile, 0)
    layer = dataSource.GetLayer()
    #属性过滤 Filter by attribute
    layer.SetAttributeFilter("name = 'A区'")
    for feature in layer:
        print(feature.GetField("name"))
    dataSource.Destroy()

# Get Geometry from each Feature in a Layer
def getGeometryfromFeature():
    shapefile = r"data\Search_Polygon.shp"
    driver = ogr.GetDriverByName("ESRI Shapefile")
    dataSource = driver.Open(shapefile, 0)
    layer = dataSource.GetLayer()
    layerdef = layer.GetLayerDefn()
    for feature in layer:
        geom = feature.GetGeometryRef()
        print(geom)
    dataSource.Destroy()

# Get Field from each Feature in a Layer
def getFeildfromFeature():
    shapefile = r"data\hubu.shp"
    driver = ogr.GetDriverByName("ESRI Shapefile")
    dataSource = driver.Open(shapefile, 0)
    layer = dataSource.GetLayer()#获取图层
    layerdef = layer.GetLayerDefn()#获取图层属性
    for i in range(layerdef.GetFieldCount()):#遍历字段
        defn = layerdef.GetFieldDefn(i)#获取每个字段对象
        print(defn.GetName(),defn.GetWidth(),defn.GetType(),defn.GetPrecision())
    name=[];code=[]#定义name和code属性值List
    for feature in layer:#获取图层中的每一个要素
        name.append(feature.GetField("name"))#获取name字段的属性信息
        code.append(feature.GetField('code'))#获取code字段的属性信息
    print(name);print(code) #输出name和code属性值
    dataSource.Destroy()#释放内存
if __name__ == '__main__':
    getFeildfromFeature()